package com.example.demo.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
public class FileService {

    // 存储文件的根目录
    private final String rootDir = "/var/www/html/fileuploads/";

    // 文件上传
    public String uploadFile(MultipartFile file) {
        try {
            // 确保目录存在
            Path uploadPath = Paths.get(rootDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件
            String fileName = file.getOriginalFilename();
            Path filePath = null;
            if (fileName != null) {
                filePath = uploadPath.resolve(fileName);
            }
            if (filePath != null) {
                // 使用 REPLACE_EXISTING 选项覆盖同名文件
                Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            }

            return fileName;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    // 文件下载
    public byte[] getFile(String fileName) {
        try {
            Path filePath = Paths.get(rootDir).resolve(fileName);
            return Files.readAllBytes(filePath);
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败: " + e.getMessage());
        }
    }

    // 获取文件类型
    public String getFileType(String fileName) {
        try {
            Path filePath = Paths.get(rootDir).resolve(fileName);
            return Files.probeContentType(filePath);  // 自动检测文件类型
        } catch (IOException e) {
            throw new RuntimeException("获取文件类型失败: " + e.getMessage());
        }
    }
}
